OUTPUT=labdoo-mega.iso

CD_DIR=cd
MOUNT_DIR=mnt
ISOLINUX=isolinux
ISOLINUX_DIR=$(CD_DIR)/$(ISOLINUX)
LABDOO_MIRROR_DIR=$(CD_DIR)/labdoo

ORIGINAL=orig/ubuntu.iso

ISOLINUX_BINARIES=$(ISOLINUX_DIR)/isolinux.bin $(ISOLINUX_DIR)/chain.c32 $(ISOLINUX_DIR)/vesamenu.c32

INCLUDE=$(CD_DIR)/boot $(CD_DIR)/doc $(CD_DIR)/install $(CD_DIR)/pics \
	$(CD_DIR)/README.diskdefines $(CD_DIR)/preseed/ubuntu.seed \
	$(CD_DIR)/.disk $(CD_DIR)/pool $(CD_DIR)/dists

REMOVE=$(CD_DIR)/install/netboot $(CD_DIR)/install/README.sbm \
       $(CD_DIR)/install/sbm.bin $(ISOLINUX_DIR)/boot.cat \
       $(shell find $(CD_DIR)/pool -name '*.deb')

DEPS=$(ISOLINUX_BINARIES) $(INCLUDE) $(ISOLINUX_DIR)/labdoo.png \
     $(ISOLINUX_DIR)/f1.txt #$(LABDOO_MIRROR_DIR)

CLEAN=$(DEPS) $(MIRROR_DIR) $(UDEBS_DIR) $(PACKAGES_DIR)/dists $(ISOLINUX_DIR)/f*.txt

ISOS="http://mirrors.mit.edu/ubuntu-releases/12.04.2/"
ISO_URL="http://mirrors.mit.edu/ubuntu-releases/12.04.2/ubuntu-12.04.2-alternate-i386.iso"

SPLASH_URL="http://labdoo-iso.googlecode.com/svn/trunk/doc/isolinux/img/splab1.png"
TXT_URL="https://labdoo-iso.googlecode.com/svn/trunk/doc/isolinux/txt"

define copy
	@echo Copying $(1) from $(MOUNT_DIR) into $(2)
	cp -r --no-preserve=timestamps $(MOUNT_DIR)/$(1) $(2)
endef


.DEFAULT_TARGET: all
.PHONY: all cleanpool clean wipe

all: $(OUTPUT)


$(OUTPUT): $(shell find $(CD_DIR)) $(DEPS)
	umount $(MOUNT_DIR) || sudo umount $(MOUNT_DIR)
	rm -rf $(MOUNT_DIR)
	rm -rf $(REMOVE)

	cd $(CD_DIR) ;\
	find . -type f  ! \( -wholename './md5sum.txt' -o -wholename './$(ISOLINUX)/*' \) -exec \
	md5sum {} \; > md5sum.txt ;\
	mkisofs -o ../$@ -r -J -l -cache-inodes \
	-no-emul-boot -boot-load-size 4 -boot-info-table \
	-b $(ISOLINUX)/isolinux.bin -c $(ISOLINUX)/boot.cat .


$(ISOLINUX_BINARIES): $(MOUNT_DIR)
	$(call copy,$(ISOLINUX)/$(notdir $@),$(ISOLINUX_DIR))


$(INCLUDE): $(MOUNT_DIR)
	$(call copy,$(shell echo $@ | sed "s/$(CD_DIR)\///"),$(CD_DIR)/$(dir $(shell echo $@ | sed "s/$(CD_DIR)\///")))


$(MOUNT_DIR):
	mkdir -p $(MOUNT_DIR)
	mount -o loop $(ORIGINAL) $(MOUNT_DIR) || sudo mount -o loop $(ORIGINAL) $(MOUNT_DIR)


$(ORIGINAL):
	wget -O $@ $(ISO_URL)


$(ISOLINUX_DIR)/labdoo.png:
	#wget -O $@ $(SPLASH_URL)


$(ISOLINUX_DIR)/f1.txt:
	#svn export --force $(TXT_URL) $(ISOLINUX_DIR)


wipe: clean
	#rm -rf $(ORIGINAL)


clean:
	rm -rf $(CLEAN)
	rm -f $(OUTPUT) $(CD_DIR)/md5sum.txt
